<?php

namespace app\api\controller;


use app\common\controller\Api;
use app\common\model\Address as ModelAddress;
use app\common\model\Area;
use app\common\model\Distributionregion;
use think\Db;
use Exception;
use think\Validate;

/**
 * 地址管理
 */
class Address extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['mate_city'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // protected $auth = ['test3'];

    /**
     * @Author LK
     * @date: 2024-08-07
     * @ApiTitle (地址匹配)
     * @ApiMethod (POST)
     * @ApiParams (name="province", type="string", required=true, sample="", description="省")
     * @ApiParams (name="city", type="string", required=true, sample="", description="市")
     * @ApiParams (name="area", type="string", required=true, sample="", description="区")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function mate_city()
    {
        $params = $this->request->param();
        extract($params);
        $validate = new Validate([
            ['city', 'require', '缺少参数']
        ]);
        if (!$validate->check($params)) {
            $this->error($validate->getError());
        }
        $provinceinfo = db('cnarea')->whereLike('short_name|name', '%' . $province . '%')->where('level', 1)->find();
        if (!$provinceinfo) {
            $this->error('地址匹配失败');
        }
        $cityinfo = db('cnarea')->whereLike('short_name|name', '%' . $city . '%')->where('parent_code', $provinceinfo['area_code'])->where('level', 2)->find();
        if (!$cityinfo) {
            $this->error('地址匹配失败');
        }
        $areainfo = db('cnarea')->whereLike('short_name|name', '%' . $area . '%')->where('parent_code', $cityinfo['area_code'])->where('level', 3)->find();
        if (!$areainfo) {
            $this->error('地址匹配失败');
        }
        $this->success('地址匹配成功');
    }
    /**
     * 创建地址
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="custom_id", type="int", required=true, description="客户ID")
     * @ApiParams (name="info", type="jsonarray", required=true, description="[{'city':'','address':'','province_id':'省ID','city_id':'市ID','area_id':'区ID'},...]")

     * @ApiParams (name="is_default", type="int", required=true, description="是否默认:0=否,1=是")
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function add()
    {

        $rej = $this->validate(
            $this->request->post(),
            [
                // 'name'  => 'require|max:25',
                'custom_id'  => 'require|gt:0',
                'info'  => 'require',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1006, [], $rej);
        }
        Db::startTrans();
        try {
            $input = $this->request->put();
            $user = $this->auth->getUser();
            $custom_id = $this->request->post('custom_id');
            $data = $input['info'];
            foreach ($data as $key => &$v) {
                $city = explode('/', $v['city']);
                if (!isset($v['province_id']) || !$v['province_id']) {
                    $provinceinfo = db('cnarea')->whereLike('short_name|name', '%' . $city[0] . '%')->where('level', 1)->find();
                    if (!$provinceinfo) {
                        exception('省错误');
                    }
                    $v['province_id'] = $provinceinfo['area_code'];
                }
                if (!isset($v['city_id']) || !$v['city_id']) {
                    $cityinfo = db('cnarea')->whereLike('short_name|name', '%' . $city[1] . '%')->where('parent_code', $provinceinfo['area_code'])->where('level', 2)->find();
                    if (!$cityinfo) {
                        exception('市错误');
                    }
                    $v['city_id'] = $cityinfo['area_code'];
                }
                if (!isset($v['area_id']) || !$v['area_id']) {
                    $areainfo = db('cnarea')->whereLike('short_name|name', '%' . $city[2] . '%')->where('parent_code', $cityinfo['area_code'])->where('level', 3)->find();
                    if (!$areainfo) {
                        exception('区错误');
                    }
                    $v['area_id'] = $areainfo['area_code'];
                }
                $v['custom_id'] = $custom_id;
                $v['user_id'] = $user->id;
            }
            $res = new ModelAddress();
            $res->saveAll($data);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
            return $e->getMessage();
        }

        $this->responseMsg(0);
    }



    /**
     * 编辑
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, description="地址ID")
     * @ApiParams (name="city", type="str", required=true, description="省市区-逗号分隔")
     * @ApiParams (name="address", type="str", required=true, description="详细地址")
     * @ApiParams (name="province_id", type="str", required=true, description="省ID")
     * @ApiParams (name="city_id", type="str", required=true, description="市ID")
     * @ApiParams (name="area_id", type="str", required=true, description="区ID")
     * @ApiParams (name="is_default", type="int", required=true, description="是否默认:0=否,1=是")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function edit()
    {
        $rej = $this->validate(
            $this->request->post(),
            [
                'id' => 'require|min:1',
                'province_id' => 'require|gt:0',
                'city_id' => 'require|gt:0',
                'area_id' => 'require|gt:0',
                'city' => 'require|max:255',
                'address' => 'require|max:255',
                // 'is_default'  => 'number',
            ],
        );
        if (true !== $rej) {
            $this->responseMsg(1006, [], $rej);
        }

        $res = ModelAddress::where('id', $this->request->post('id'))->find();
        if (!$res) {
            $this->responseMsg(1005, [], '未找到该地址');
        }
        $user = $this->auth->getUser();

        if ($res->user_id != $user->id) {
            $this->responseMsg(1006, [], '权限错误');
        }
        $data = $this->request->post();
        $city = explode('/', $data['city']);
        if (!isset($param['province_id']) || !$param['province_id']) {
            $provinceinfo = db('cnarea')->whereLike('short_name|name', '%' . $city[0] . '%')->where('level', 1)->find();
            if (!$provinceinfo) {
                $this->error('省错误');
            }
            $data['province_id'] = $provinceinfo['area_code'];
        }
        if (!isset($param['city_id']) || !$param['city_id']) {
            $cityinfo = db('cnarea')->whereLike('short_name|name', '%' . $city[1] . '%')->where('parent_code', $provinceinfo['area_code'])->where('level', 2)->find();
            if (!$cityinfo) {
                $this->error('市错误');
            }
            $city['city_id'] = $cityinfo['area_code'];
        }
        if (!isset($param['area_id']) || !$param['area_id']) {
            $areainfo = db('cnarea')->whereLike('short_name|name', '%' . $city[2] . '%')->where('parent_code', $cityinfo['area_code'])->where('level', 3)->find();
            if (!$areainfo) {
                $this->error('区错误');
            }
            $city['area_id'] = $areainfo['area_code'];
        }
        // $res->name = $data['name'];
        // $res->mobile = $data['mobile'];
        $res->citys = $data['city'];
        $res->address = $data['address'];
        $res->is_default = $data['is_default'];
        $res->province_id = $data['province_id'];
        $res->city_id = $data['city_id'];
        $res->area_id = $data['area_id'];
        $res->save();
        $this->responseMsg(0);
    }


    /**
     * 列表
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="custom_id", type="int", required=true, description="客户ID")
     * 
     * @ApiReturnParams (name="code", type="integer", required=true, sample="0")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function list()
    {
        $rej = $this->validate(
            $this->request->post(),
            [
                // 'name'  => 'require|max:25',
                'custom_id'  => 'require|gt:0',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1006, [], $rej);
        }
        $user = $this->auth->getUser();
        $res = ModelAddress::where('custom_id', $this->request->post('custom_id'))->order('id desc')->select();
        $this->responseMsg(0, $res);
    }


    /**
     * 详情
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, description="地址ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function detail()
    {
        $rej = $this->validate(
            $this->request->post(),
            [
                'id'  => 'require|number',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $user = $this->auth->getUser();

        $res = ModelAddress::get($this->request->post('id'));
        if (!$res) {
            $this->responseMsg(1005, [], '未找到该内容');
        }
        $this->responseMsg(0, $res);
    }

    /**
     * 删除地址
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, description="地址ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function del()
    {
        $rej = $this->validate(
            $this->request->post(),
            [
                'id'  => 'require|number|egt:1',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $user = $this->auth->getUser();

        $res = ModelAddress::get($this->request->post('id'));
        if (!$res) {
            $this->responseMsg(1005, [], '未找到该地址');
        }
        if ($res->user_id != $user->id) {
            $this->responseMsg(1005, [], '没得权限');
        }
        $res->delete();
        $this->responseMsg(0, '', '删除成功');
    }


    /**
     * 设置默认
     * @Author xy
     * @ApiTitle 
     * @ApiMethod (POST)
     * @ApiParams (name="id", type="integer", required=true, description="地址ID")
     * @ApiReturnParams (name="code", type="integer", required=true, description="")
     * @ApiReturn ({'code':0,'msg':'返回成功'})
     */
    public function setdefault()
    {
        $rej = $this->validate(
            $this->request->post(),
            [
                'id'  => 'require|number|egt:1',
            ]
        );
        if (true !== $rej) {
            $this->responseMsg(1005, [], $rej);
        }
        $user = $this->auth->getUser();

        $res = ModelAddress::get($this->request->post('id'));
        if (!$res) {
            $this->responseMsg(1005, [], '未找到该地址');
        }
        if ($res->user_id != $user->id) {
            $this->responseMsg(1005, [], '没得权限');
        }
        $res->is_default = 1;
        $res->save();
        $this->responseMsg(0);
    }
}
